from Products.KnowledgeEngine.KERL.Tokens.Token import Token
from Products.KnowledgeEngine.KERL.Operators import *
from Products.KnowledgeEngine.Services.MySQLFiveAssessmentStorageService.MySQLFiveAssessmentStorageService import qstr, qlist
from Products.KnowledgeEngine.KERL.Tokens.ComponentToken import ComponentToken
from Products.KnowledgeEngine.KERLProcessor import ComponentNotFound, InvalidKerlExpression
from DateTime import DateTime
   
import types


class PreviousOperator(ComponentToken):
    """ 
        Implements the [reference,previous] functionality 
        HACK - This Operator actually functions as both an Operator and a Token
    """

    _implements = ComponentToken._implements + ("PreviousOperator",)
    
    def __init__(self, a, b):
        """ Initializes the reference operator """
        
        # 'a' will always be the ReferenceToken,
        # 'b' contains the name of the component class to reference
        
        namespace        = a.namespace
        currentComponent = namespace['component']        
        section          = currentComponent.aq_parent
        lookFor          = b and b.getObject() # The class name to look for
                
        previous = currentComponent.getPreviousComponentByInstanceOf( lookFor )
        
        if not previous:
            raise ComponentNotFound, "Cannot find previous component"
        
        print "Previous Component: " + previous.absolute_url()
        
        self.object = previous
                
        #componentsInSection = section.getChildren()
            
        #currentIndex        = componentsInSection.index( currentComponent )
        
        #while 1:
            #referencedComponent = componentsInSection[ currentIndex - 1 ]
            #if (not lookFor) or referencedComponent.isInstanceOf( lookFor ):
                #break
            
            #currentIndex-=1
            
            #if currentIndex == 0:
                #raise ComponentNotFound, "Could not find reference component in expression: [reference,previous,%s]" % ( lookFor )
                
        #self.object = referencedComponent # Assign the referenced component as the target object for the ReferenceToken.
                                       ## From here on it, it will function 
                
    
   
class ReferenceToken(ComponentToken):
                
    _implements = ComponentToken._implements + ("ReferenceToken",)
    
    operators = {
        'previous': PreviousOperator
    }    
    
    def __init__(self, namespace):
        
        self.namespace = namespace
        self.object    = None
        
        
                
   